<?php
/**
* 게시판 쓰기 기본 로직 처리
* /ezbbs/logic/default/insert.php
* hamhaja <hamhaja@nextez.co.kr>
* 2006-10-28
*/
if (!isset($is_board_logic_include)) exit;

// 클래스 인스턴스
$App->class_require('File');
$App->class_require('Image');
$App->class_require('Random');
$App->class_require('Table.EzbbscnfArtcat');
$App->class_require('Table.EzbbscnfAdd');
$App->class_require('Table.EzbbsFile');
$App->class_require('Table.EzbbsLink');
$App->class_require('Table.EzbbsAdd');
$File			= new File();
$Image			= new Image();
$Ramdom			= new Random(false, true, true);
$EzbbscnfArtcat	= new EzbbscnfArtcat(&$Db);
$EzbbscnfAdd	= new EzbbscnfAdd(&$Db);
$EzbbsFile		= new EzbbsFile(&$Db, $EzbbsManager->get_dir_data());
$EzbbsLink		= new EzbbsLink(&$Db);
$EzbbsAdd		= new EzbbsAdd(&$Db);

// 초기화
$subjob = $App->nvl('subjob', 'form');

if ($subjob == 'form')
{
	if ((!$eb_seq && $EzbbsManager->auth(BOARD_INSERT_AUTH)) || ($eb_seq && $EzbbsManager->auth(BOARD_ANSWER_AUTH)))
	{

		// get category list
		if ($_set['artcat_flag'])
		{
			$category_list = & $EzbbscnfArtcat->category_list($ebcf_id);
			if (!count($category_list)) $_set['artcat_flag'] = false;
		}

		// get add column list
		$add_column_list = & $EzbbscnfAdd->add_list($ebcf_id, true);

		//if ($EzbbsManager->use_spam() && $EzbbsManager->is_guest()) $EzbbsManager->set_spam($Ramdom->get(5));
		/*****************************************************************************
		* 게시물 입력번호가 넘겨진경우는 답글로 처리
		*****************************************************************************/
		$source_subject = $source_text = '';
		if ($eb_seq)
		{
			$source_record = & $Ezbbs->get_a_record('eb_name, eb_subject, eb_txt, eb_ctime', array($ebcf_id, $eb_seq));
			if (!$source_record) $Error->fail(NOT_FIND_DATA, null, -1);

			$Ezbbs->htmlchars($source_record);
			$source_record['eb_ctime'] = date("{$_set['view_date']}", $source_record['eb_ctime']);
			$source_record['eb_txt'] = ereg_replace("^\n+|\n+$", "", $source_record['eb_txt']);
			$source_record['eb_txt'] = ereg_replace("\n", "\n>", $source_record['eb_txt']);

			$source_subject = "[RE]" . $source_record['eb_subject'];
			$source_text = "\n\n\n>" . $source_record['eb_subject'] . '(' . $source_record['eb_name'] . ' / ' . $source_record['eb_ctime'] . ')';
			$source_text .= "\n\n>" . $source_record['eb_txt'];
		}
		/*****************************************************************************
		* FCKEditor
		*****************************************************************************/
		if ($_set['editor_flag'])
		{
//			require_once $App->_dir_root . '/fckeditor/fckeditor.php';
//			$EDITOR = new FCKeditor('eb_txt');
//			$EDITOR->Height = '400';
//			$EDITOR->ToolbarSet = 'Default';
			//$EDITOR->Value = $source_text;

			require_once $App->_dir_root . '/ckeditor/ckeditor.php';
			require_once $App->_dir_root . '/ckfinder/ckfinder.php';
			// 경로 지정
			$ckeditor->basePath = $App->_dir_root . '/ckeditor/';
			$ckeditor = new CKEditor();

			$ckeditor->config['skin'] = 'v2';
			$ckeditor->config['width'] = '660';
			$ckeditor->config['height'] = '400';
			$ckeditor->config['enterMode'] = '2';
			$ckeditor->config['shiftEnterMode'] = '3';

			CKFinder::SetupCKEditor($ckeditor, $ckeditor->basePath);

		}
		/*****************************************************************************
		* input print column
		*****************************************************************************/
		$_print = array();
		foreach ($_set['input_list'] as $v)
			$_print[$v] = true;

		if (!$eb_seq && !$_set['gallery_flag'] && $_set['notice_flag'] && $EzbbsManager->is_admin())
			$_set['notice'] = true;

		// set template
		 array_push($board_tpls, 'insert_form');
	}
	else
	{
		if (!$User->is_login()) array_push($board_tpls, 'login_form');
		else $Error->set(AUTH_FAIL);
	}
}
else if ($subjob == 'ok')
{
	if (!$App->check_method(POST)) $Error->fail(NO_PERMIT_METHOD);

	if ((!$eb_seq && $EzbbsManager->auth(BOARD_INSERT_AUTH)) || ($eb_seq && $EzbbsManager->auth(BOARD_ANSWER_AUTH)))
	{
		/*****************************************************************************
		* 스펨차단 적용지 .. 입력값 체크
		*****************************************************************************/
//		if ($EzbbsManager->use_spam())
//		{
//			// 보류
//		}
		/*****************************************************************************
		* 데이타보정
		*****************************************************************************/

		$_POST['eb_ebcfid'] = $ebcf_id;
		if ($_POST['eb_seq'])
		{
			if (!$Ezbbs->set_family_thread($ebcf_id, $eb_seq, &$_POST)) $Error->fail(NOT_FIND_DATA);
		}
		else $_POST['eb_family_seq'] = $Ezbbs->get_family_seq($ebcf_id);


		// set options
		if (!$_POST['eb_html_flag']) $_POST['eb_html_flag'] = false;
		if (!$_POST['eb_br_flag']) $_POST['eb_br_flag'] = false;

		// set seq
		$_POST['eb_seq'] = $Ezbbs->get_seq($ebcf_id);

		/*****************************************************************************
		* 첨부파일 업로드
		*****************************************************************************/
		if (isset($_FILES) && count($_FILES))
		{
			$dir_path = $EzbbsFile->get_dir() . "/" . date('Ym');
			if (($msg = $File->new_directory($dir_path, 0777, false)) != '') $Error->fail(DIR_CREATE_FAIL, $msg);
			$exts = split('\|', $_set['ext_list']);
			if (($msg = $File->can_upload($_FILES, $dir_path, 'rename', $exts, $_set['ext_flag'])) != '') $Error->fail(FILE_UPLOAD_FAIL, $msg);
		}


		/*****************************************************************************
		* 데이터 체크
		*****************************************************************************/
		$_POST['eb_subject'] = sprintf("%s",$_POST['eb_subject']);
		$_POST['eb_name'] = sprintf("%s",$_POST['eb_name']);
		$_POST['eb_eml'] = sprintf("%s",$_POST['eb_eml']);
		$_POST['eb_txt'] = sprintf("%s",$_POST['eb_txt']);

		/*****************************************************************************
		* 게시물 추가
		*****************************************************************************/
		if ($Ezbbs->insert($_POST, array('eb_cid', 'eb_ctime', 'eb_cip')))
		{
			/*****************************************************************************
			* 첨부파일
			*****************************************************************************/
			if (isset($_FILES))
			{
				$serial = 1;
				foreach ($_FILES as $k => $v)
				{
					if (empty($v['name'])) continue;
					$saved_file = $File->upload_a_file($v, $dir_path, 'rename', $exts, $_set['ext_flag'], true, uniqid(''));
					if ($saved_file)
					{
						$image_info = getimagesize($saved_file);
						$ext = $File->get_extension($saved_file);
						$cols = array(
							'ebfi_ebcfid'	=> $_POST['ebcf_id'],
							'ebfi_ebseq'	=> $_POST['eb_seq'],
							'ebfi_no'		=> $serial++,
							'ebfi_pname'	=> $v['name'],
							'ebfi_path'		=> str_replace($EzbbsFile->get_dir(), '', $saved_file),
							'ebfi_size'		=> $v['size'],
							'ebfi_width'	=> $image_info ? $image_info[0] : 0,
							'ebfi_height'	=> $image_info ? $image_info[1] : 0,
							'ebfi_include'	=> ($image_info[2]>=1 && $image_info[2]<=16) ? true : false,
							'ebfi_ext'		=> $ext,
						);
						if ($EzbbsFile->insert($cols))
						{
							////////// 미리보기 이미지 자동생성
							if ($EzbbsFile->is_image($cols['ebfi_path']) && ($cols['ebfi_width'] > EZBBS_IMAGE_THUMBNAIL_WIDTH))
								$Image->make_thumbnail($saved_file, EZBBS_IMAGE_THUMBNAIL_WIDTH);
						}
						else $Error->fail(FILE_UPLOAD_FAIL, false);
					}
				}
			}
			/*****************************************************************************
			* 첨부링크
			*****************************************************************************/
			if (isset($_POST['ebln_path']) && is_array($_POST['ebln_path']))
			{
				$serial = 1;
				for ($i=0; $i<count($_POST['ebln_path']); $i++)
				{
					$path = trim($_POST['ebln_path'][$i]);
					if (empty($path)) continue;
					$cols = array(
						'ebln_ebcfid'	=> $_POST['ebcf_id'],
						'ebln_ebseq'	=> $_POST['eb_seq'],
						'ebln_serial'	=> $serial++,
						'ebln_path'		=> $_POST['ebln_path'][$i],
						'ebln_target'	=> 'B',
					);
					$EzbbsLink->insert($cols);
				}
			}
			/*****************************************************************************
			* 추가항목
			*****************************************************************************/
			if ($_POST['ebad_id'] && count($_POST['ebad_id']))
			{
				foreach ($_POST['ebad_id'] as $k => $v)
				{
					if (trim($_POST['ebad_txt'][$k]) == '') continue;
					$cols = array(
						'ebad_ebcfid'	=> $_POST['ebcf_id'],
						'ebad_ebseq'	=> $_POST['eb_seq'],
						'ebad_ebcfadid' => $v,
						'ebad_txt'		=> $_POST['ebad_txt'][$k],
					);
					$EzbbsAdd->insert($cols);
				}
			}

			/*****************************************************************************
			* 완료 후 문자 OR 메일 발송
			*****************************************************************************/
			if ($_set['admsms_flag'] || $_set['admmail_flag'])
			{
				/*
				$App->class_require('HttpClient.Sms');
				$App->class_require('SmtpMail');
				$Sms = new SmsHttpClient();
				$SMTPMAIL = new SmtpMail();

				$list = $EzbbsManager->get_admin_info();

				if($list)
				{
					$msg = $_set['name']." 게시판에 새로운 글이 등록되었습니다.";
					foreach($list as $k => $v)
					 $App->send_message($msg,$v['mb_hp'], $v['mb_eml']);

				}
				*/
			}

			/*****************************************************************************
			* 작업완료후 처리
			*****************************************************************************/
			if (isset($_POST['eb_pw'])) $EzbbsManager->set_pass($_POST['eb_pw']);
			$EzbbsManager->set_spam(null);

			if (!$EzbbsManager->auth(BOARD_VIEW_AUTH))
			{
				$next_job = 'list';
				$Success->success(INSERT_SUCCESS, '', false);
			}
			else
			{
				$next_job = 'detail';
				$paras['eb_seq'] = $_POST['eb_seq'];
			}
			$next_url = $paras['mid'] ? $App->_url_sub . '/index.php' : $_SERVER['PHP_SELF'];
			$Script->location($next_url . "?job={$next_job}&" . http_build_query($paras), 'parent');

		}
		else $Error->fail(INSERT_FAIL);
	}
	else $Error->fail(AUTH_FAIL);
}
?>